//*- coding = utf-8 -*-
//@Time : 2022-10-19 0:14
//@Author : 管茂良
//@File : utils.js
//@web  : www.php-china.com
//@Software: WebStorm
import {ComponentInternalInstance, getCurrentInstance} from "vue";
import {useI18n} from "vue-i18n";

type typeInterface = "navigateBack" | "navigateTo" | "switchTab" | "reLaunch" | "redirectTo"
export function handlePageTo(type:typeInterface, url:string) {
    if (type == "navigateBack") {
        // 关闭当前页，返回上一页面或多级页面。
        uni.navigateBack({
            delta: parseInt(url),
            animationType: 'pop-out',
            animationDuration: 300,
            fail:(res)=>{
                console.log(res);
            }
        });
    } else if (type == "navigateTo") {
        // 保留当前页，跳转到非tabbar页面，使用uni.navigateBack可以返回到原页面。
        uni.navigateTo({
            url: url+"",
            animationType: 'pop-in',
            animationDuration: 300,
            fail:(res)=>{
                console.log(res);
            }
        })
    } else if (type == "switchTab") {
        // 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面。
        uni.switchTab({
            url: url,
            fail:(res)=>{
                console.log(res);
            }
        })
    } else if (type == "reLaunch") {
        // 关闭所有页面，打开到应用内的某个页面。
        uni.reLaunch({
            url: url,
            fail:(res)=>{
                console.log(res);
            }
        })
    } else if (type == "redirectTo") {
        // 关闭当前页面，跳转到应用内的某个页面。
        uni.redirectTo({
            url: url,
        });
    }
}

// 当前时间
export function handleCurrentTime(fmt:string){
    const date = new Date()
    var o:any = {
        "M+": date.getMonth() + 1, //月份
        "d+": date.getDate(), //日
        "h+": date.getHours(), //小时
        "m+": date.getMinutes(), //分
        "s+": date.getSeconds(), //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

// 获取任意时间
export function getDate(date:any, AddDayCount = 0) {
    if (!date) {
        date = new Date()
    }
    if (typeof date !== 'object') {
        date = date.replace(/-/g, '/')
    }
    const dd = new Date(date)

    dd.setDate(dd.getDate() + AddDayCount) // 获取AddDayCount天后的日期

    const y = dd.getFullYear()
    const m = dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1 // 获取当前月份的日期，不足10补0
    const d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate() // 获取当前几号，不足10补0
    return {
        fullDate: y + '-' + m + '-' + d,
        year: y,
        month: m,
        date: d,
        day: dd.getDay()
    }
}

/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params: { [x: string]: any; }) {
    let result = ''
    for (const propName of Object.keys(params)) {
        const value = params[propName];
        var part = encodeURIComponent(propName) + "=";
        if (value !== null && typeof (value) !== "undefined") {
            if (typeof value === 'object') {
                for (const key of Object.keys(value)) {
                    if (value[key] !== null && typeof (value[key]) !== 'undefined') {
                        let params = propName + '[' + key + ']';
                        var subPart = encodeURIComponent(params) + "=";
                        result += subPart + encodeURIComponent(value[key]) + "&";
                    }
                }
            } else {
                result += part + encodeURIComponent(value) + "&";
            }
        }
    }
    return result
}

/**
 * 判断数据类型
 */
export const handleDataType = ()=>{
    let curCtx:any;
    curCtx.prototype.handleIsArray=(data:Array<any>)=>{
        return Object.prototype.toString.call(data) === "[object Array]"?true:false;
    }
    curCtx.prototype.handleIsNumber=(data:number)=>{
        return Object.prototype.toString.call(data) === "[object Number]"?true:false;
    }
    curCtx.prototype.handleIsString=(data:string)=>{
        return Object.prototype.toString.call(data) === "[object String]"?true:false;
    }
    curCtx.prototype.handleIsBoolean=(data:boolean)=>{
        return Object.prototype.toString.call(data) === "[object Boolean]"?true:false;
    }
    curCtx.prototype.handleIsNull=(data:null)=>{
        return Object.prototype.toString.call(data) === "[object Null]"?true:false;
    }
    curCtx.prototype.handleIsUndefined=(data:undefined)=>{
        return Object.prototype.toString.call(data) === "[object Undefined]"?true:false;
    }
    curCtx.prototype.handleIsFunction=(data:Function)=>{
        return Object.prototype.toString.call(data) === "[object Function]"?true:false;
    }
    curCtx.prototype.handleIsDate=(data:Date)=>{
        return Object.prototype.toString.call(data) === "[object Date]"?true:false;
    }
    curCtx.prototype.handleIsRegExp=(data:RegExp)=>{
        return Object.prototype.toString.call(data) === "[object RegExp]"?true:false;
    }
    curCtx.prototype.handleIsError=(data:Error)=>{
        return Object.prototype.toString.call(data) === "[object Error]"?true:false;
    }
    return curCtx;
}
//获取当前页面的上下文
export function handleGetCurInstance(){
    const {appContext,proxy} = getCurrentInstance() as ComponentInternalInstance
    let globalProperties = appContext.config.globalProperties;
    let axios = globalProperties.$axios;
    let model = globalProperties.$model;
    let tab = globalProperties.$tab;
    let download = globalProperties.$download;
    let auth = globalProperties.$auth;
    let dict = globalProperties.$dict;
    let i18n = useI18n();
    return {
        globalProperties,proxy,
        axios,model,tab,download,auth,dict,i18n
    }
}

//判断是否为json格式数据
export const handleIsJSON = (str) => {
    if (typeof str == 'string') {
        try {
            let obj=JSON.parse(str);
            if(typeof obj == 'object' && obj ){
                return true;
            }else{
                return false;
            }
        } catch(e) {
            console.log('error：'+str+'!!!'+e);
            return false;
        }
    }
    return true;
}

// 日期格式化
export function handleParseTime(time:string|number, pattern?:string) {
    if (arguments.length === 0 || !time) {
        return null
    }
    const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
            time = parseInt(time)
        } else if (typeof time === 'string') {
            time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
            time = time * 1000
        }
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
        if (result.length > 0 && value < 10) {
            value = '0' + value
        }
        return value || 0
    })
    return time_str
}

